// cnpm i express socket.io -D
// nodemon index.js
// 添加ws服务
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
let connectionList = [];
http.listen(3000, () => {
    console.log('listening on *:3000');
});
const CLIENT_RTC_EVENT = 'CLIENT_RTC_EVENT';
const SERVER_RTC_EVENT = 'SERVER_RTC_EVENT';

const CLIENT_USER_EVENT = 'CLIENT_USER_EVENT';
const SERVER_USER_EVENT = 'SERVER_USER_EVENT';

const CLIENT_USER_EVENT_LOGIN = 'CLIENT_USER_EVENT_LOGIN';
const SERVER_USER_EVENT_UPDATE_USERS = 'SERVER_USER_EVENT_UPDATE_USERS';

function getOnlineUser() {
    return connectionList
        .filter(item => {
            return item.userName !== '';
        })
        .map(item => {
            return {
                userName: item.userName,
                roomId: item.roomId,
                roomName: item.roomName
            };
        });
}

function setUserName(connection, payload) {
    connectionList.forEach(item => {
        if (item.connection.id === connection.id) {
            item.userName = payload.userName;
            item.roomId = payload.roomId;
            item.roomName = payload.roomName;
        }
    });
}

function updateUsers(connection) {
    connection.emit(SERVER_USER_EVENT, { type: SERVER_USER_EVENT_UPDATE_USERS, payload: getOnlineUser() });
}
// 用户连接
io.on('connection', function (connection) {
    // 加入未命名用户
    connectionList.push({
        connection: connection,
        userName: '',
        roomId: '',
        roomName: ''
    });

    // 连接上 的用户，推送在线 用户列表
    updateUsers(connection);
    // 创建用户
    connection.on(CLIENT_USER_EVENT, function (jsonString) {
        const msg = JSON.parse(jsonString);
        const { type, payload } = msg;

        if (type === CLIENT_USER_EVENT_LOGIN) {
            // 给用户命名
            setUserName(connection, payload);
            // 更新用户列表
            connectionList.forEach(item => {
                updateUsers(item.connection);
            });
        }
    });
    // 监听RTC事件
    connection.on(CLIENT_RTC_EVENT, function (jsonString) {
        const msg = JSON.parse(jsonString);
        const { payload } = msg;
        const target = payload.target;

        const targetConn = connectionList.find(item => {
            return item.roomId === target;
        });
        if (targetConn) {
            targetConn.connection.emit(SERVER_RTC_EVENT, msg);
        }
    });
    // 断开连接事件
    connection.on('disconnect', function () {
        // 去掉断开连接的
        connectionList = connectionList.filter(item => {
            return item.connection.id !== connection.id;
        });
        connectionList.forEach(item => {
            updateUsers(item.connection);
        });
    });
});